package cppweb.example.ibatis;

import javax.sql.DataSource;

import cppweb.spring.ibatis.MybatisUtils;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.internal.DefaultShellCallback;
import org.mybatis.spring.annotation.MapperScan;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = {DataSourceConfig.BASE_NAME + ".dao", DataSourceConfig.BASE_NAME + ".mapper"}, sqlSessionFactoryRef = DataSourceConfig.FACTORY_NAME)
class DataSourceConfig{
	static final String TABLE_PATTERN = "T_XG_USER";
    public final static String POOL_NAME = "default";
    public final static String BASE_NAME = "cppweb.example";
    public final static String CONFIG_NAME = "database.config." + POOL_NAME;
    public final static String FACTORY_NAME = "database.factory." + POOL_NAME;

	@Bean(CONFIG_NAME)
	public DataSource getDataSource(){
		return MybatisUtils.createDataSource(POOL_NAME);
	}

	@Bean(FACTORY_NAME)
	public SqlSessionFactory getSessionFactory(@Qualifier(CONFIG_NAME) DataSource datasource) throws Exception{
		return MybatisUtils.createSessionFactory(datasource, DataSourceConfig.class);
	}

	public static void main(String[] args){
		List<String> warnings = new ArrayList<>();
		DefaultShellCallback callback = new DefaultShellCallback(true);

		try{
			new MyBatisGenerator(MybatisUtils.getGeneratorConfig(POOL_NAME, TABLE_PATTERN, BASE_NAME + ".mapper"), callback, warnings).generate(null);
		}
		catch (Exception e){
			e.printStackTrace();
		}

		for (String warning : warnings){
			System.out.println(warning);
		}

		System.out.flush();
		System.exit(0);
	}
}